using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Input;
using Newtonsoft.Json;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.MVVM_Model.Plan;

namespace WPF_MVVM_Test.MVVM_ViewModel.Plan
{
    /// <summary>
    /// 新增/编辑生产计划ViewModel
    /// </summary>
    public class AddProductPlanViewModel : BaseViewModel
    {
        #region 事件
        /// <summary>
        /// 请求返回列表页面事件 - 使用ProductPlanViewModel的导航事件
        /// </summary>
        public static event Action? RequestBackToList;
        #endregion

        #region 私有字段
        private Guid _id = Guid.Empty;  // 编辑模式时使用原ID，新增模式时为空
        private string _planNumber = string.Empty;
        private string _planName = string.Empty;
        private Guid _bomId = Guid.Empty;  // 不显示，后续BOM选择时赋值
        private string _orderNumber = string.Empty;
        private string _productName = string.Empty;
        private string _productNumber = string.Empty;
        private string _specification = string.Empty;
        private string _productType = string.Empty;
        private string _unit = string.Empty;
        private decimal _planQuantity = 0;
        private DateTime _planStartTime = DateTime.Today;
        private DateTime _planEndTime = DateTime.Today.AddDays(7);
        private DateTime _requiredDate = DateTime.Today.AddDays(10);
        private string? _remark = string.Empty;
        private int _status = 0;  // 默认未分解，不显示
        private string? _attachment = string.Empty;
        private string _selectedSourceType = "销售订单";
        private bool _isAutoGenerateNumber = false;
        private string _selectedBomInfo = "暂无数据";
        private bool _showBomWarning = true;
        private bool _hasBomComponents = false;
        private ObservableCollection<BomComponent> _bomComponents = new();
        private ObservableCollection<BomTreeNode> _bomTree = new();
        public ObservableCollection<BomTreeNode> BomTree
        {
            get => _bomTree;
            set => SetProperty(ref _bomTree, value);
        }
        #endregion

        #region 公共属性
        /// <summary>
        /// 计划编号
        /// </summary>
        public string PlanNumber
        {
            get => _planNumber;
            set => SetProperty(ref _planNumber, value);
        }

        /// <summary>
        /// 计划名称
        /// </summary>
        public string PlanName
        {
            get => _planName;
            set => SetProperty(ref _planName, value);
        }

        /// <summary>
        /// 订单编号
        /// </summary>
        public string OrderNumber
        {
            get => _orderNumber;
            set => SetProperty(ref _orderNumber, value);
        }

        /// <summary>
        /// 成品名称
        /// </summary>
        public string ProductName
        {
            get => _productName;
            set => SetProperty(ref _productName, value);
        }

        /// <summary>
        /// 成品编号
        /// </summary>
        public string ProductNumber
        {
            get => _productNumber;
            set => SetProperty(ref _productNumber, value);
        }

        /// <summary>
        /// 规格型号
        /// </summary>
        public string Specification
        {
            get => _specification;
            set => SetProperty(ref _specification, value);
        }

        /// <summary>
        /// 成品类型
        /// </summary>
        public string ProductType
        {
            get => _productType;
            set => SetProperty(ref _productType, value);
        }

        /// <summary>
        /// 单位
        /// </summary>
        public string Unit
        {
            get => _unit;
            set => SetProperty(ref _unit, value);
        }

        /// <summary>
        /// 计划数量
        /// </summary>
        public decimal PlanQuantity
        {
            get => _planQuantity;
            set => SetProperty(ref _planQuantity, value);
        }

        /// <summary>
        /// 开工时间
        /// </summary>
        public DateTime PlanStartTime
        {
            get => _planStartTime;
            set => SetProperty(ref _planStartTime, value);
        }

        /// <summary>
        /// 完工时间
        /// </summary>
        public DateTime PlanEndTime
        {
            get => _planEndTime;
            set => SetProperty(ref _planEndTime, value);
        }

        /// <summary>
        /// 需求日期
        /// </summary>
        public DateTime RequiredDate
        {
            get => _requiredDate;
            set => SetProperty(ref _requiredDate, value);
        }

        /// <summary>
        /// 备注
        /// </summary>
        public string? Remark
        {
            get => _remark;
            set => SetProperty(ref _remark, value);
        }

        /// <summary>
        /// 选中的来源类型
        /// </summary>
        public string SelectedSourceType
        {
            get => _selectedSourceType;
            set => SetProperty(ref _selectedSourceType, value);
        }

        /// <summary>
        /// 是否自动生成编号
        /// </summary>
        public bool IsAutoGenerateNumber
        {
            get => _isAutoGenerateNumber;
            set => SetProperty(ref _isAutoGenerateNumber, value);
        }

        /// <summary>
        /// 来源类型选项
        /// </summary>
        public List<SourceTypeOption> SourceTypes { get; }

        /// <summary>
        /// 已上传文件列表
        /// </summary>
        public ObservableCollection<UploadedFile> UploadedFiles { get; }

        /// <summary>
        /// 选中的BOM信息
        /// </summary>
        public string SelectedBomInfo
        {
            get => _selectedBomInfo;
            set => SetProperty(ref _selectedBomInfo, value);
        }

        /// <summary>
        /// 是否显示BOM警告
        /// </summary>
        public bool ShowBomWarning
        {
            get => _showBomWarning;
            set => SetProperty(ref _showBomWarning, value);
        }

        /// <summary>
        /// 是否有BOM组件
        /// </summary>
        public bool HasBomComponents
        {
            get => _hasBomComponents;
            set => SetProperty(ref _hasBomComponents, value);
        }

        /// <summary>
        /// BOM组件列表
        /// </summary>
        public ObservableCollection<BomComponent> BomComponents
        {
            get => _bomComponents;
            set => SetProperty(ref _bomComponents, value);
        }

        /// <summary>
        /// 是否为编辑模式
        /// </summary>
        public bool IsEditMode => Id != Guid.Empty;

        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle => IsEditMode ? "编辑生产计划" : "新增生产计划";
        #endregion

        #region 公共属性 - 隐藏字段
        /// <summary>
        /// 主键ID - 编辑模式时使用原ID，新增模式时为空
        /// </summary>
        public Guid Id
        {
            get => _id;
            set => SetProperty(ref _id, value);
        }

        /// <summary>
        /// BOM ID - 不显示在页面，选择BOM时赋值
        /// </summary>
        public Guid BomId
        {
            get => _bomId;
            set => SetProperty(ref _bomId, value);
        }

        /// <summary>
        /// 状态 - 不显示在页面，默认为0(未分解)
        /// </summary>
        public int Status
        {
            get => _status;
            set => SetProperty(ref _status, value);
        }

        /// <summary>
        /// 来源类型 - 对应SelectedSourceType的值
        /// </summary>
        public string SourceType => SelectedSourceType;
        #endregion

        #region 命令
        public ICommand GenerateNumberCommand { get; }
        public ICommand SelectOrderCommand { get; }
        public ICommand SelectProductCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand SelectFileCommand { get; }
        public ICommand RemoveFileCommand { get; }
        public ICommand SelectBomCommand { get; }
        #endregion

        #region 构造函数
        public AddProductPlanViewModel()
        {
            // 初始化集合
            UploadedFiles = new ObservableCollection<UploadedFile>();

            // 初始化来源类型选项
            SourceTypes = new List<SourceTypeOption>
            {
                new SourceTypeOption { Value = "销售订单", Text = "销售订单" },
                new SourceTypeOption { Value = "生产订单", Text = "生产订单" },
                new SourceTypeOption { Value = "库存补充", Text = "库存补充" },
                new SourceTypeOption { Value = "其他", Text = "其他" }
            };

            // 初始化命令
            GenerateNumberCommand = CreateCommand(GenerateNumber);
            SelectOrderCommand = CreateCommand(SelectOrder);
            SelectProductCommand = CreateCommand(SelectProduct);
            SaveCommand = CreateCommand(Save);
            SelectFileCommand = CreateCommand(SelectFile);
            RemoveFileCommand = CreateCommand<UploadedFile>(RemoveFile);
            SelectBomCommand = CreateCommand(SelectBom);

            // 设置默认值
            PlanStartTime = DateTime.Today;
            PlanEndTime = DateTime.Today.AddDays(7);
            RequiredDate = DateTime.Today.AddDays(10);
        }
        #endregion

        #region 私有方法

        /// <summary>
        /// 初始化编辑数据
        /// </summary>
        /// <param name="plan">要编辑的生产计划</param>
        public void InitializeEditData(ProductplanModel plan)
        {
            if (plan == null) return;

            // 设置编辑模式
            Id = plan.Id;
            
            // 反填数据
            PlanNumber = plan.PlanNumber ?? string.Empty;
            PlanName = plan.PlanName ?? string.Empty;
            SelectedSourceType = plan.SourceType ?? "销售订单";
            OrderNumber = plan.OrderNumber ?? string.Empty;
            ProductName = plan.ProductName ?? string.Empty;
            ProductNumber = plan.ProductNumber ?? string.Empty;
            ProductType = plan.ProductType ?? string.Empty;
            Specification = plan.Specification ?? string.Empty;
            Unit = plan.Unit ?? string.Empty;
            PlanQuantity = plan.PlanQuantity;
            PlanStartTime = plan.PlanStartTime ?? DateTime.Today;
            PlanEndTime = plan.PlanEndTime ?? DateTime.Today.AddDays(7);
            RequiredDate = plan.RequiredDate ?? DateTime.Today.AddDays(10);
            Remark = plan.Remark ?? string.Empty;
            Status = plan.Status;
            
            // 处理BOM ID
            if (Guid.TryParse(plan.BomId, out var bomGuid))
                BomId = bomGuid;
            else
                BomId = Guid.Empty;

            // 如果有BOM信息，显示BOM信息
            if (BomId != Guid.Empty)
            {
                SelectedBomInfo = $"BOM ID: {BomId} - 产品: {ProductName}";
            }

            // 通知属性变更
            OnPropertyChanged(nameof(IsEditMode));
            OnPropertyChanged(nameof(PageTitle));
            OnPropertyChanged(nameof(PlanNumber));
            OnPropertyChanged(nameof(PlanName));
            OnPropertyChanged(nameof(SelectedSourceType));
            OnPropertyChanged(nameof(OrderNumber));
            OnPropertyChanged(nameof(ProductName));
            OnPropertyChanged(nameof(ProductNumber));
            OnPropertyChanged(nameof(ProductType));
            OnPropertyChanged(nameof(Specification));
            OnPropertyChanged(nameof(Unit));
            OnPropertyChanged(nameof(PlanQuantity));
            OnPropertyChanged(nameof(PlanStartTime));
            OnPropertyChanged(nameof(PlanEndTime));
            OnPropertyChanged(nameof(RequiredDate));
            OnPropertyChanged(nameof(Remark));
            OnPropertyChanged(nameof(SelectedBomInfo));
        }

        /// <summary>
        /// 生成系统编号
        /// </summary>
        private void GenerateNumber()
        {
            // 生成格式：SCJH + 年月日时分秒毫秒
            // 左半部分：SCJH（生产计划缩写）
            // 右半部分：年月日时分秒毫秒（yyyyMMddHHmmssfff）
            var now = DateTime.Now;
            var timestamp = now.ToString("yyyyMMddHHmmssfff");
            PlanNumber = $"SCJH{timestamp}";
            IsAutoGenerateNumber = true;

            // 显示生成成功的提示
            System.Windows.MessageBox.Show($"已生成系统编号：{PlanNumber}", "系统编号生成",
                System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
        }

        /// <summary>
        /// 选择订单
        /// </summary>
        private void SelectOrder()
        {
            try
            {
                var dialog = new WPF_MVVM_Test.MVVM_View.Dialog.SelectSalesOrderDialog();
                
                // 设置父窗口
                if (System.Windows.Application.Current.MainWindow != null)
                {
                    dialog.Owner = System.Windows.Application.Current.MainWindow;
                }
                
                // 显示对话框
                if (dialog.ShowDialog() == true && dialog.SelectedSalesOrder != null)
                {
                    var selectedOrder = dialog.SelectedSalesOrder;
                    
                    // 设置选中的订单信息
                    OrderNumber = selectedOrder.SalesCode;
                    
                    // 可以根据需要设置其他相关字段
                    if (string.IsNullOrEmpty(PlanName))
                    {
                        PlanName = $"{selectedOrder.SalesName}生产计划";
                    }
                    
                    System.Windows.MessageBox.Show($"已选择销售订单：{selectedOrder.SalesCode} - {selectedOrder.SalesName}", "提示",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"打开销售订单选择对话框失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 选择产品
        /// </summary>
        private void SelectProduct()
        {
            try
            {
                var dialog = new WPF_MVVM_Test.MVVM_View.Dialog.SelectProductDialog();
                
                if (System.Windows.Application.Current.MainWindow != null)
                {
                    dialog.Owner = System.Windows.Application.Current.MainWindow;
                }
                
                if (dialog.ShowDialog() == true && dialog.SelectedProduct != null)
                {
                    var selectedProduct = dialog.SelectedProduct;
                    
                    // 只填充产品相关信息，不修改时间字段
                    ProductName = selectedProduct.MaterialName;
                    ProductNumber = selectedProduct.MaterialNumber;
                    Specification = selectedProduct.SpecificationModel;
                    ProductType = selectedProduct.MaterialType ?? "成品";
                    Unit = selectedProduct.Unit;
                    
                    System.Windows.MessageBox.Show($"已选择产品：{selectedProduct.MaterialNumber} - {selectedProduct.MaterialName}", "提示",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"打开产品选择对话框失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        private async void Save()
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(PlanNumber))
                {
                    System.Windows.MessageBox.Show("请输入计划编号！", "验证失败");
                    return;
                }

                if (string.IsNullOrWhiteSpace(PlanName))
                {
                    System.Windows.MessageBox.Show("请输入计划名称！", "验证失败");
                    return;
                }

                if (string.IsNullOrWhiteSpace(ProductName))
                {
                    System.Windows.MessageBox.Show("请选择产品！", "验证失败");
                    return;
                }

                if (PlanQuantity <= 0)
                {
                    System.Windows.MessageBox.Show("请输入有效的计划数量！", "验证失败");
                    return;
                }

                using var service = new WPF_MVVM_Test.Services.Plan.ProductPlanService();
                bool success = false;

                if (IsEditMode)
                {
                    // 编辑模式 - 更新现有计划
                    var updateModel = new UpdateProductplanModel
                    {
                        Id = Id,
                        PlanNumber = PlanNumber,
                        PlanName = PlanName,
                        BomId = BomId,
                        SourceType = SourceType,
                        OrderNumber = OrderNumber,
                        ProductName = ProductName,
                        ProductNumber = ProductNumber,
                        ProductType = ProductType,
                        Specification = Specification,
                        Unit = Unit,
                        PlanQuantity = PlanQuantity,
                        PlanStartTime = PlanStartTime,
                        PlanEndTime = PlanEndTime,
                        RequiredDate = RequiredDate,
                        Remark = Remark,
                        Status = Status,
                        Attachment = GetAttachmentString()
                    };

                    success = await service.UpdateProductPlanAsync(updateModel);
                }
                else
                {
                    // 新增模式 - 创建新计划
                    var productPlan = new AddProductplanModel
                    {
                        Id = Guid.Empty,  // 后端生成ID
                        PlanNumber = PlanNumber,
                        PlanName = PlanName,
                        BomId = BomId,
                        SourceType = SourceType,
                        OrderNumber = OrderNumber,
                        ProductName = ProductName,
                        ProductNumber = ProductNumber,
                        ProductType = ProductType,
                        Specification = Specification,
                        Unit = Unit,
                        PlanQuantity = PlanQuantity,
                        PlanStartTime = PlanStartTime,
                        PlanEndTime = PlanEndTime,
                        RequiredDate = RequiredDate,
                        Remark = Remark,
                        Status = 0,  // 默认未分解
                        Attachment = GetAttachmentString()
                    };

                    success = await service.CreateProductPlanAsync(productPlan);
                }

                if (success)
                {
                    string message = IsEditMode ? "生产计划更新成功！" : "生产计划创建成功！";
                    System.Windows.MessageBox.Show(message, "提示", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    
                    // 如果是编辑模式，关闭弹框
                    if (IsEditMode)
                    {
                        // 查找父窗口并设置DialogResult
                        var parentWindow = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>()
                            .FirstOrDefault(w => w.IsActive && w.DataContext == this);
                        if (parentWindow != null)
                        {
                            parentWindow.DialogResult = true;
                            parentWindow.Close();
                        }
                    }
                    else
                    {
                        // 新增模式，返回列表页面
                        BackToList();
                    }
                }
                else
                {
                    string message = IsEditMode ? "更新失败，请重试！" : "创建失败，请重试！";
                    System.Windows.MessageBox.Show(message, "错误", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                string message = IsEditMode ? "更新失败" : "保存失败";
                System.Windows.MessageBox.Show($"{message}：{ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取附件字符串
        /// </summary>
        private string GetAttachmentString()
        {
            if (UploadedFiles.Count == 0)
                return string.Empty;
            
            // 将附件路径用分号分隔
            return string.Join(";", UploadedFiles.Select(f => f.FilePath));
        }

        /// <summary>
        /// 返回列表页面
        /// </summary>
        private void BackToList()
        {
            // 通过事件通知主窗口切换页面
            var mainWindow = System.Windows.Application.Current.MainWindow;
            if (mainWindow?.DataContext is MainWindowViewModel mainViewModel)
            {
                if (mainViewModel.ShowProductPlanCommand.CanExecute(null))
                {
                    mainViewModel.ShowProductPlanCommand.Execute(null);
                }
            }
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        private void SelectFile()
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Title = "选择附件",
                Filter = "所有支持的文件|*.docx;*.doc;*.xls;*.xlsx;*.pdf;*.rar;*.zip;*.png;*.jpg;*.jpeg|" +
                        "Word文档|*.docx;*.doc|" +
                        "Excel文档|*.xls;*.xlsx|" +
                        "PDF文档|*.pdf|" +
                        "压缩文件|*.rar;*.zip|" +
                        "图片文件|*.png;*.jpg;*.jpeg|" +
                        "所有文件|*.*",
                Multiselect = true
            };

            if (openFileDialog.ShowDialog() == true)
            {
                foreach (var fileName in openFileDialog.FileNames)
                {
                    var fileInfo = new System.IO.FileInfo(fileName);
                    var uploadedFile = new UploadedFile
                    {
                        FileName = fileInfo.Name,
                        FilePath = fileName,
                        FileSize = FormatFileSize(fileInfo.Length)
                    };
                    UploadedFiles.Add(uploadedFile);
                }
            }
        }

        /// <summary>
        /// 移除文件
        /// </summary>
        private void RemoveFile(UploadedFile file)
        {
            if (file != null)
            {
                UploadedFiles.Remove(file);
            }
        }

        private async Task LoadBomTreeAsync(string bomId)
        {
            if (string.IsNullOrWhiteSpace(bomId)) return;
            try
            {
                using (var client = new HttpClient())
                {
                    var url = $"http://8.140.242.140:8888/api/ProductionPlans/bom-structure/{bomId}";
                    var response = await client.GetStringAsync(url);
                    var result = JsonConvert.DeserializeObject<BomTreeApiResponse>(response);
                    BomTree.Clear();
                    if (result != null && result.data != null)
                    {
                        foreach (var node in result.data)
                            BomTree.Add(node);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"💥 加载BOM树异常: {ex.Message}");
            }
        }
        // BOM树API响应模型
        public class BomTreeApiResponse
        {
            public List<BomTreeNode> data { get; set; }
            public bool isSuc { get; set; }
            public int code { get; set; }
            public string msg { get; set; }
        }

        /// <summary>
        /// 选择BOM
        /// </summary>
        private void SelectBom()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("🔍 SelectBom方法开始执行");
                
                if (string.IsNullOrWhiteSpace(ProductName))
                {
                    ShowBomWarning = true;
                    System.Windows.MessageBox.Show("请先选择成品！", "提示");
                    System.Diagnostics.Debug.WriteLine("❌ 产品名称为空，显示警告");
                    return;
                }

                ShowBomWarning = false;
                System.Diagnostics.Debug.WriteLine($"✅ 产品名称: {ProductName}");
                
                // 创建产品信息
                var productInfo = new WPF_MVVM_Test.MVVM_Model.Plan.ProductBomInfo
                {
                    ProductName = ProductName,
                    ProductNumber = ProductNumber,
                    Specification = Specification,
                    Unit = Unit
                };

                System.Diagnostics.Debug.WriteLine("📦 创建产品信息对象完成");

                // 创建对话框
                System.Diagnostics.Debug.WriteLine("🪟 开始创建SelectBomDialog");
                var dialog = new WPF_MVVM_Test.MVVM_View.Dialog.SelectBomDialog(productInfo);
                System.Diagnostics.Debug.WriteLine("✅ SelectBomDialog创建成功");
                
                // 设置父窗口
                if (System.Windows.Application.Current.MainWindow != null)
                {
                    dialog.Owner = System.Windows.Application.Current.MainWindow;
                    System.Diagnostics.Debug.WriteLine("✅ 设置父窗口成功");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("⚠️ 主窗口为空");
                }
                
                System.Diagnostics.Debug.WriteLine("🪟 准备显示对话框");
                var dialogResult = dialog.ShowDialog();
                System.Diagnostics.Debug.WriteLine($"📋 对话框结果: {dialogResult}");
                
                if (dialogResult == true && dialog.SelectedBom != null)
                {
                    var selectedBom = dialog.SelectedBom;
                    System.Diagnostics.Debug.WriteLine($"✅ 选择了BOM: {selectedBom.BomCode}");
                    
                    // 更新BOM ID
                    if(Guid.TryParse(selectedBom.Id, out var bomGuid))
                    {
                        BomId = bomGuid;
                        // 新增：选择BOM后自动加载BOM树
                        _ = LoadBomTreeAsync(selectedBom.Id);
                        System.Diagnostics.Debug.WriteLine($"✅ BOM ID解析成功: {bomGuid}");
                    }
                    else
                    {
                        BomId = Guid.Empty;
                        System.Diagnostics.Debug.WriteLine("⚠️ BOM ID解析失败，设置为空");
                    }
                    
                    // 更新产品相关信息
                    ProductName = selectedBom.ProductName;
                    ProductNumber = selectedBom.ProductId;
                    Specification = selectedBom.ColorCode;
                    Unit = selectedBom.Unit;
                    
                    // 更新BOM信息显示
                    SelectedBomInfo = $"已选择BOM：{selectedBom.BomCode} 版本：{selectedBom.Version}";
                    
                    // 通知属性变更
                    OnPropertyChanged(nameof(ProductName));
                    OnPropertyChanged(nameof(ProductNumber));
                    OnPropertyChanged(nameof(Specification));
                    OnPropertyChanged(nameof(Unit));
                    OnPropertyChanged(nameof(SelectedBomInfo));
                    
                    System.Windows.MessageBox.Show($"已选择BOM：{selectedBom.BomCode}", "提示",
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("❌ 对话框未返回true或未选择BOM");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"💥 SelectBom方法发生异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"💥 异常堆栈: {ex.StackTrace}");
                
                System.Windows.MessageBox.Show($"打开BOM选择对话框失败：{ex.Message}\n\n详细错误：{ex.StackTrace}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB" };
            double len = bytes;
            int order = 0;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len = len / 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }
        #endregion
    }

    /// <summary>
    /// 来源类型选项
    /// </summary>
    public class SourceTypeOption
    {
        public string Value { get; set; } = string.Empty;
        public string Text { get; set; } = string.Empty;
    }

    /// <summary>
    /// 上传文件信息
    /// </summary>
    public class UploadedFile
    {
        public string FileName { get; set; } = string.Empty;
        public string FilePath { get; set; } = string.Empty;
        public string FileSize { get; set; } = string.Empty;
    }

    // BOM组件数据模型
    public class BomComponent
    {
        public string ComponentName { get; set; } = string.Empty;
        public string ComponentCode { get; set; } = string.Empty;
        public decimal Quantity { get; set; }
        public string Unit { get; set; } = string.Empty;
    }

    /// <summary>
    /// 更新生产计划模型
    /// </summary>
    public class UpdateProductplanModel
    {
        public Guid Id { get; set; }
        public string PlanNumber { get; set; } = string.Empty;
        public string PlanName { get; set; } = string.Empty;
        public Guid BomId { get; set; }
        public string SourceType { get; set; } = string.Empty;
        public string OrderNumber { get; set; } = string.Empty;
        public string ProductName { get; set; } = string.Empty;
        public string ProductNumber { get; set; } = string.Empty;
        public string ProductType { get; set; } = string.Empty;
        public string Specification { get; set; } = string.Empty;
        public string Unit { get; set; } = string.Empty;
        public decimal PlanQuantity { get; set; }
        public DateTime? PlanStartTime { get; set; }
        public DateTime? PlanEndTime { get; set; }
        public DateTime? RequiredDate { get; set; }
        public string Remark { get; set; } = string.Empty;
        public int Status { get; set; }
        public string Attachment { get; set; } = string.Empty;
    }
}








